<template>
  <div class="course-detail">
    <!-- 顶部蓝色背景区域 -->
    <div class="blue-header">
      <div class="header-content">
        <div class="title-info">
          <h1>{{ currentCourse?.name }}</h1>
          <span class="time">开课时间：{{ currentCourse?.startTime }} - {{ currentCourse?.endTime }}</span>
        </div>
        <div class="user-actions">
          <div class="icon-btn">📱</div>
          <div class="icon-btn">🔔</div>
          <div class="user-info">
            <span class="avatar">我</span>
            <span>我的学习</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 功能按钮组 -->
    <div class="function-bar">
      <div class="function-content">
        <div class="button-group">
          <button class="nav-btn active">课程内容</button>
          <button class="nav-btn">知识考核</button>
          <button class="nav-btn">能力考核</button>
          <button class="nav-btn">实验管理</button>
          <button class="nav-btn">通知公告</button>
          <button class="nav-btn" @click="handleStudentManagement">学生管理</button>
        </div>
        <div class="right-buttons">
          <button class="outline-btn">运行数据</button>
          <button class="outline-btn">课程设置</button>
        </div>
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="content-container">
      <div class="tab-list">
        <div class="tab" :class="{ active: currentTab === 'catalog' }" @click="currentTab = 'catalog'">目录</div>
        <div class="tab" :class="{ active: currentTab === 'materials' }" @click="currentTab = 'materials'">学习资料(0)</div>
        <div class="tab" :class="{ active: currentTab === 'homework' }" @click="currentTab = 'homework'">作业任务(0)</div>
        <div class="tab" :class="{ active: currentTab === 'exam' }" @click="currentTab = 'exam'">考试任务(0)</div>
        <div class="tab" :class="{ active: currentTab === 'experiment' }" @click="currentTab = 'experiment'">实验任务(0)</div>
        <div class="tab" :class="{ active: currentTab === 'training' }" @click="currentTab = 'training'">实训任务(1)</div>
        <div class="tab" :class="{ active: currentTab === 'discussion' }" @click="currentTab = 'discussion'">讨论内容(0)</div>
        <div class="tab" :class="{ active: currentTab === 'interactive' }" @click="currentTab = 'interactive'">互动课堂(2)</div>
        <div class="tab" :class="{ active: currentTab === 'live' }" @click="currentTab = 'live'">直播课堂(0)</div>
      </div>

      <!-- 内容区域 - 添加条件渲染 -->
      <div v-if="currentTab === 'catalog'" class="content-main">
        <div class="content-tools">
          <button class="tool-btn" @click="toggleAllModules">
            目录{{ isAllExpanded ? '收起' : '展开' }}
          </button>
        </div>

        <div class="content-list" v-if="courseStructure">
          <!-- 遍历模块 -->
          <div v-for="module in courseStructure.modules" :key="module.id" class="module">
            <div class="module-header" @click="toggleModule(module.id)">
              <div class="module-title">
                <span>{{ module.name }}</span>
              </div>
              <div class="module-actions">
                <button class="action-btn" title="删除" @click="handleDeleteModule(module.id, $event)">
                  <i class="icon">🗑️</i>
                </button>
                <button class="action-btn" title="展开/收起">
                  <i class="icon">{{ module.isExpanded ? '▼' : '▶' }}</i>
                </button>
              </div>
            </div>
            
            <!-- 课时列表 -->
            <div v-show="module.isExpanded">
              <div class="module-items">
                <div v-for="lesson in module.lessons" 
                     :key="lesson.id" 
                     class="sub-item">
                  <div class="sub-item-content">
                    <span>{{ lesson.name }}</span>
                    <div class="sub-item-actions">
                      <button class="sub-action-btn" title="删除" @click="handleDeleteLesson(lesson.id, $event)">
                        <i class="icon">🗑️</i>
                      </button>
                      <button class="sub-action-btn" 
                              title="展开/收起" 
                              @click.stop="toggleSubItem(module.id, lesson.id)">
                        <i class="icon">{{ lesson.isExpanded ? '▼' : '▶' }}</i>
                      </button>
                    </div>
                  </div>
                  
                  <!-- 课时内容 -->
                  <div v-show="lesson.isExpanded" class="third-level">
                    <!-- 显示已有内容 -->
                    <template v-if="lesson.contents.length > 0">
                      <div v-for="content in lesson.contents" 
                           :key="content.id" 
                           class="doc-item">
                        <div class="doc-content" @click="handlePreview(content)">
                          <span>{{ content.name }}</span>
                          <span class="doc-info">{{ content.size }}</span>
                        </div>
                        <div class="doc-actions">
                          <button class="doc-btn" @click="handlePreview(content)">预览</button>
                          <button class="doc-btn" @click="handleDeleteContent(content.id, $event)">删除</button>
                        </div>
                      </div>
                    </template>
                    
                    <!-- 操作按钮组 -->
                    <div class="action-group">
                      <button class="action-group-btn" @click="handleUploadClick(lesson)">+ 文档</button>
                      <button class="action-group-btn" @click="handleVideoUploadClick(lesson)">+ 视频</button>
                      <button class="action-group-btn">+ 资料</button>
                      <button class="action-group-btn">+ 链接</button>
                      <button class="action-group-btn">+ 作业</button>
                      <button class="action-group-btn">+ 考试</button>
                      <button class="action-group-btn">+ 实验</button>
                      <button class="action-group-btn">+ 实训</button>
                      <button class="action-group-btn">+ 讨论</button>
                      <button class="action-group-btn">+ 直播</button>
                    </div>
                  </div>
                </div>
              </div>
              
              <!-- 添加课时按钮 -->
              <div class="add-course">
                <button class="add-btn" @click="handleAddLessonClick(module.id)">
                  <span class="plus-icon">+</span>
                  添加课时
                </button>
              </div>
            </div>
          </div>

          <!-- 添加模块按钮 -->
          <div class="add-module">
            <button class="add-btn" @click="showAddModuleDialog = true">
              <span class="plus-icon">+</span>
              添加模块
            </button>
          </div>
        </div>
      </div>

      <!-- 互动课堂组件 -->
      <interactive-classroom v-else-if="currentTab === 'interactive'" />
    </div>

    <!-- 添加模块对话框 -->
    <el-dialog
      v-model="showAddModuleDialog"
      title="添加模块"
      width="30%"
      :before-close="handleClose"
    >
      <el-form :model="moduleForm" label-width="80px">
        <el-form-item label="模块名称">
          <el-input 
            v-model="moduleForm.name" 
            placeholder="请输入模块名称"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleAddModule">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加课时对话框 -->
    <el-dialog
      v-model="showAddLessonDialog"
      title="添加课时"
      width="30%"
      :before-close="handleLessonClose"
    >
      <el-form :model="lessonForm" label-width="80px">
        <el-form-item label="课时名称">
          <el-input 
            v-model="lessonForm.name" 
            placeholder="请输入课时名称"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleLessonClose">取消</el-button>
          <el-button type="primary" @click="handleAddLesson">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 文档上传对话框 -->
    <el-dialog
      v-model="showUploadDialog"
      title="上传文档"
      width="30%"
      :before-close="handleUploadClose"
    >
      <el-form :model="uploadForm" label-width="80px">
        <el-form-item label="上传文件">
          <el-upload
            ref="uploadRef"
            class="upload-demo"
            :before-upload="beforeUpload"
            accept=".doc,.docx,.ppt,.pptx,.pdf"
          >
            <el-button type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持 .doc、.docx、.ppt、.pptx、.pdf 格式文件
              </div>
            </template>
          </el-upload>
          <div v-if="uploadStates.document.value" class="upload-status">{{ uploadStates.document.value }}</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleUploadClose">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 视频上传对话框 -->
    <el-dialog
      v-model="showVideoUploadDialog"
      title="上传视频"
      width="30%"
      :before-close="handleVideoUploadClose"
    >
      <el-form :model="videoUploadForm" label-width="80px">
        <el-form-item label="上传视频">
          <el-upload
            class="upload-demo"
            :before-upload="beforeVideoUpload"
            accept=".mp4,.avi,.mov,.wmv,.flv"
          >
            <el-button type="primary">选择视频</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持 .mp4、.avi、.mov、.wmv、.flv 格式视频文件
              </div>
            </template>
          </el-upload>
          <div v-if="uploadStates.video.value" class="upload-status">{{ uploadStates.video.value }}</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleVideoUploadClose">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 学生管理对话框 -->
    <el-dialog
      v-model="showStudentManagementDialog"
      title="学生管理"
      width="900px"
      :before-close="handleStudentManagementClose"
    >
      <div class="student-management">
        <!-- 顶部搜索和操作区 -->
        <div class="operation-bar">
          <el-input
            v-model="searchQuery"
            placeholder="搜索学号/姓名/手机号/邮箱"
            class="search-input"
            clearable
            @clear="handleSearch"
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-button type="primary" @click="handleAddStudent" class="add-student-btn">
            添加学生
          </el-button>
        </div>

        <!-- 表格区域 -->
        <el-table
          :data="filteredStudents"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="studentId" label="学号" width="140" />
          <el-table-column prop="name" label="姓名" width="100" />
          <el-table-column prop="phone" label="手机号" min-width="140" />
          <el-table-column label="操作" width="180">
            <template #default="scope">
              <el-button link type="primary" @click="handleStudentLog(scope.row)">学生日志</el-button>
              <el-button link type="primary" @click="handleQuit(scope.row)">退课</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 无数据时的提示 -->
        <el-empty
          v-if="showEmptyText"
          description="当前课堂无学生，请添加！"
        />
      </div>
    </el-dialog>

    <!-- 添加右侧滑出的添加学生抽屉 -->
    <el-drawer
      v-model="showAddStudentDrawer"
      title="添加学生"
      direction="rtl"
      size="50%"
      :destroy-on-close="true"
      class="add-student-drawer"
    >
      <div class="drawer-content">
        <!-- 左目录树 -->
        <div class="directory-tree">
          <div class="tree-header">
            <el-button
              type="primary"
              class="excel-import-btn"
              @click="handleExcelImport"
            >
              Excel导入
            </el-button>
            <el-input
              v-model="orgSearchQuery"
              placeholder="组织名称"
              class="org-search-input"
              clearable
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
          <el-tree
            ref="treeRef"
            :data="organizationTree"
            :props="defaultProps"
            @node-click="handleNodeClick"
            default-expand-all
            :expand-on-click-node="false"
            highlight-current
          />
          <div class="selected-count">
            选：{{ selectedCandidateStudents.length }} 人
          </div>
        </div>

        <!-- 右侧生列 -->
        <div class="student-list">
          <el-input
            v-model="studentSearchQuery"
            placeholder="学号/姓名/手号/邮箱"
            class="student-search-input"
            clearable
            @blur="handleStudentSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>

          <!-- 学生表格 -->
          <el-table
            :data="filteredCandidateStudents"
            style="width: 100%"
            @selection-change="handleCandidateSelectionChange"
            height="calc(100vh - 200px)"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="studentId" label="学号" width="140" />
            <el-table-column prop="name" label="姓名" width="100" />
            <el-table-column prop="phone" label="手机号" min-width="140" />
          </el-table>
        </div>
      </div>

      <!-- 底部操按钮 -->
      <template #footer>
        <div class="drawer-footer">
          <el-button @click="showAddStudentDrawer = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmAdd">添加</el-button>
        </div>
      </template>
    </el-drawer>

    <!-- 在 el-drawer 组件内添加 Excel 上传对话框 -->
    <el-dialog
      v-model="showExcelUploadDialog"
      title="Excel入"
      width="30%"
      :before-close="handleExcelDialogClose"
    >
      <el-upload
        class="excel-upload"
        :show-file-list="false"
        :limit="1"
        :before-upload="beforeExcelUpload"
        :action="uploadExcelUrl"
        :data="uploadExcelData"
        :on-success="handleExcelUploadSuccess"
        :on-error="handleExcelUploadError"
        accept=".xlsx,.xls"
      >
        <el-button type="primary">选择文件</el-button>
        <template #tip>
          <div class="el-upload__tip">
            请上传 Excel 文件（.xlsx, .xls）
          </div>
        </template>
      </el-upload>

      <!-- 上传状态显示 -->
      <div class="upload-status" v-if="uploadStates.excel.value">
        <el-alert
          :title="uploadStates.excel.value"
          :type="uploadStates.type.value"
          :closable="false"
          show-icon
        />
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleExcelDialogClose">取消</el-button>
          <el-button type="primary" @click="handleExcelDialogConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 预览对话框 -->
    <el-dialog
      v-model="showPreviewDialog"
      :title="isVideoPreview ? '视频预览' : '文档预览'"
      width="80%"
      :fullscreen="true"
      :before-close="() => showPreviewDialog = false"
    >
      <!-- 视频预览 -->
      <div v-if="isVideoPreview" class="preview-container">
        <div class="preview-content">
          <video 
            class="preview-video" 
            controls 
            :src="previewVideo"
          >
            您的浏览器不支持 video 标签。
          </video>
        </div>
      </div>
      
      <!-- 文档预览 -->
      <div v-else class="preview-container">
        <div class="preview-content">
          <img 
            v-for="(url, index) in previewImages" 
            :key="index"
            :src="url"
            class="preview-image"
            alt="预览图片"
          />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import InteractiveClassroom from './InteractiveClassroom.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import axios from "axios";

const route = useRoute()
const currentCourse = ref(null)

// 扩展课程据以包含所有课程
const courseData = {
  1: {
    id: 1,
    name: '年级-八年级一班',
    startTime: '2024-12-01',
    endTime: '2024-12-01',
    teacher: '田思泽'
  },
  2: {
    id: 2,
    name: '九年级-九级班',
    startTime: '2024-12-02',
    endTime: '2024-12-02',
    teacher: '田思'
  }
}

// 修改 isAllExpanded 计算属性
const isAllExpanded = computed(() => {
  if (!courseStructure.value?.modules) return false

  // 检查所有模块是否展开
  const allModulesExpanded = courseStructure.value.modules.every(module => module.isExpanded)
  // 检查所有课时否展开
  const allLessonsExpanded = courseStructure.value.modules.every(module =>
    module.lessons.every(lesson => lesson.isExpanded)
  )
  return allModulesExpanded && allLessonsExpanded
})

// 切换模块展开/收起状态
const toggleModule = (moduleId) => {
  const module = courseStructure.value.modules.find(m => m.id === moduleId)
  if (module) {
    module.isExpanded = !module.isExpanded
  }
}

// 切换子项目展开/收起状态
const toggleSubItem = (moduleId, lessonId) => {
  const module = courseStructure.value.modules.find(m => m.id === moduleId)
  if (module) {
    const lesson = module.lessons.find(l => l.id === lessonId)
    if (lesson) {
      lesson.isExpanded = !lesson.isExpanded
    }
  }
}

// 切换所有目录的展开/起状态
const toggleAllModules = () => {
  const newState = !isAllExpanded.value
  courseStructure.value.modules.forEach(module => {
    module.isExpanded = newState
    module.lessons.forEach(lesson => {
      lesson.isExpanded = newState
    })
  })
}

const currentTab = ref('catalog')

// 添加新的响应式变量
const showAddModuleDialog = ref(false)
const moduleForm = ref({
  name: ''
})

// 添加课时相关的响应式变量
const showAddLessonDialog = ref(false)
const lessonForm = ref({
  name: ''
})
const currentModuleKey = ref('') // 用于录当前要添加课时的模块

// 文档上传相关的响应式变量
const uploadRef = ref(null)
const showUploadDialog = ref(false)
const uploadForm = ref({
  file: null
})
const currentItem = ref(null) // 用于记录当前要添加文档的课时项

// 视频上传相关的响应式变量
const showVideoUploadDialog = ref(false)
const videoUploadForm = ref({
  file: null
})
const currentVideoItem = ref(null)

// 上传相关的配置和方法
const uploadAction = '/api/upload' // 替换为实际的上传接口地址

// 关闭对话框
const handleClose = () => {
  showAddModuleDialog.value = false
  moduleForm.value.name = ''
}

// 处理添加模块
const handleAddModule = async () => {
  if (!moduleForm.value.name.trim()) {
    ElMessage.warning('请输入模块名称')
    return
  }

  try {
    // 获取当前课程ID
    const classId = route.params.id

    const response = await axios.post('http://localhost:8080/catalog/addModule', 
      {
        classId: classId,
        modelName: moduleForm.value.name.trim()
      },
      {
        headers: {
          'Content-Type': 'application/json'
        }
      }
    )

    if (response.data.code === 200) {
      ElMessage.success('添加模块成功')
      // 关闭对话框
      handleClose()
      // 重新获取课程结构数据
      await fetchCourseStructure()
    } else {
      throw new Error(response.data.msg || '添加失败')
    }
  } catch (error) {
    console.error('添加模块失败:', error)
    ElMessage.error(error.message || '添加模块失败，请重试')
  }
}

// 修改添加课按的点击处理函数
const handleAddLessonClick = (moduleId) => {
  currentModuleKey.value = moduleId
  showAddLessonDialog.value = true
}

// 处理添加课时
const handleAddLesson = async () => {
  if (!lessonForm.value.name.trim()) {
    ElMessage.warning('请输入课时名称')
    return
  }

  try {
    // 获取当前课程ID和块ID
    const classId = route.params.id
    const pid = currentModuleKey.value

    const response = await axios.post('http://localhost:8080/catalog/addClassHours', 
      {
        pid: pid,
        classId: classId,
        modelName: lessonForm.value.name.trim()
      },
      {
        headers: {
          'Content-Type': 'application/json'
        }
      }
    )

    if (response.data.code === 200) {
      ElMessage.success('添加课时成功')
      // 关闭对话框
      handleLessonClose()
      // 重新获取课程结构数据
      await fetchCourseStructure()
    } else {
      throw new Error(response.data.msg || '添加失败')
    }
  } catch (error) {
    console.error('添��课时失败:', error)
    ElMessage.error(error.message || '添加课时失败，请重试')
  }
}

// 关闭课时对话框
const handleLessonClose = () => {
  showAddLessonDialog.value = false
  lessonForm.value.name = ''
  currentModuleKey.value = ''
}

// 修改处理文档按钮点击
const handleUploadClick = (lesson) => {
  currentItem.value = lesson
  showUploadDialog.value = true
}

// 统一管理所有上传相关的状态
const uploadStates = {
  document: ref(''),  // 文档上传状态
  video: ref(''),     // 视频上传状态
  excel: ref(''),     // Excel上传状态
  type: ref('info')   // 一的状态类型
}

// 修改文档上传前证
const beforeUpload = async (file) => {
  const validTypes = [
    'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'application/vnd.ms-powerpoint',
    'application/vnd.openxmlformats-officedocument.presentationml.presentation',
    'application/pdf'
  ]
  
  if (!validTypes.includes(file.type)) {
    ElMessage.error('请上传正确的文件格式！')
    return false
  }

  uploadStates.document.value = '上传中...'  // 设置上传状态

  try {
    // 创建 FormData 对象
    const formData = new FormData()
    formData.append('file', file)
    formData.append('pid', currentItem.value.id)
    formData.append('classId', route.params.id)

    // 发送上传请求
    const response = await fetch('http://192.168.100.53:8080/file/upload', {
      method: 'POST',
      body: formData
    })

    const data = await response.json()

    if (data.code === 200) {
      uploadStates.document.value = '上传成功'  // 更新上传状态
      ElMessage.success('文件上传成功')
      await fetchCourseStructure()
    } else {
      throw new Error(data.msg || '上传失')
    }
  } catch (error) {
    console.error('文件上传失:', error)
    ElMessage.error(error.message || '文件上传失败，请重试')
    uploadStates.document.value = ''  // 清空上传状态
    return false
  }

  return false
}

// 关闭上传对话框
const handleUploadClose = () => {
  showUploadDialog.value = false
  uploadForm.value.file = null
  currentItem.value = null
}

// 处理视频钮点击
const handleVideoUploadClick = (lesson) => {
  currentVideoItem.value = lesson
  showVideoUploadDialog.value = true
}

// 关闭视频上传对话框
const handleVideoUploadClose = () => {
  showVideoUploadDialog.value = false
  videoUploadForm.value.file = null
  currentVideoItem.value = null
}

// 修改视频上传前验证
const beforeVideoUpload = async (file) => {
  const validTypes = [
    'video/mp4',
    'video/avi',
    'video/quicktime',
    'video/x-ms-wmv',
    'video/x-flv'
  ]
  
  if (!validTypes.includes(file.type)) {
    ElMessage.error('请上传正确的视频格式！')
    return false
  }

  uploadStates.video.value = '上传中...'  // 设置上传状态

  try {
    // 创建 FormData 对象
    const formData = new FormData()
    formData.append('file', file)
    formData.append('classId', route.params.id)
    formData.append('pid', currentVideoItem.value.id)

    // 发送上传请求
    const response = await fetch('http://192.168.100.53:8080/upload/video', {
      method: 'POST',
      body: formData
    })

    const data = await response.json()

    if (data.code === 200) {
      uploadStates.video.value = '上传成功'  // 更新上传状态
      ElMessage.success('视频上传成功')
      await fetchCourseStructure()
    } else {
      throw new Error(data.msg || '上传失败')
    }
  } catch (error) {
    console.error('视频上传失败:', error)
    ElMessage.error(error.message || '视频上传失败，请重试')
    uploadStates.video.value = ''  // 清空上传状态
    return false
  }

  return false
}

// 学生管理相关的响应式变量
const showStudentManagementDialog = ref(false)
const searchQuery = ref('')
const selectedStudents = ref([])

// 修改模拟的学生数据，移除不需要的字段
const students = ref([])
const showEmptyText = ref(false)

// 根搜索条件过滤学生
const filteredStudents = computed(() => {
  if (showEmptyText.value) return []
  if (!searchQuery.value) return students.value
  
  const query = searchQuery.value.toLowerCase()
  return students.value.filter(student => 
    student.studentId.toLowerCase().includes(query) ||
    student.name.toLowerCase().includes(query) ||
    student.phone.toLowerCase().includes(query)
  )
})

// 处理搜索
const handleSearch = () => {
  // 可以添加外部的搜索逻辑
}

// 处理表选择化
const handleSelectionChange = (selection) => {
  selectedStudents.value = selection
}

// 将发送消息改为学生日志
const handleStudentLog = (student) => {
  ElMessage.success(`查看学生日志: ${student.name}`)
}

// 修改处理单个学生退课的函数
const handleQuit = async (student) => {
  try {
    const response = await axios.get('http://localhost:8080/user/delClassStuByStuId', {
      params: {
        userId: student.studentId,
        classId: route.params.id
      }
    })

    if (response.data.code === 200) {
      ElMessage.success('退课成功')
      // 从列表中移除该学生
      students.value = students.value.filter(s => s.studentId !== student.studentId)
    } else {
      ElMessage.error('退课失败')
    }
  } catch (error) {
    console.error('退课请求失败:', error)
    ElMessage.error('退课失败')
  }
}

// 关闭学生管理对话框
const handleStudentManagementClose = () => {
  showStudentManagementDialog.value = false
  searchQuery.value = ''
  selectedStudents.value = []
}

// 修改组织树相关的代码
const organizationTree = ref([])

// 添加一个将扁平数据转换为树形结构的函数
const convertToTreeData = (flatData) => {
  const treeData = []
  const map = {}

  // 首先创建所节点的映射
  flatData.forEach(item => {
    map[item.id] = {
      id: item.id,
      label: item.name,
      children: []
    }
  })

  // 构建树形结构
  flatData.forEach(item => {
    const node = map[item.id]
    if (item.pid === 0) {
      // 根节点
      treeData.push(node)
    } else {
      // 节点，找到父节点并添加到其children中
      const parent = map[item.pid]
      if (parent) {
        parent.children.push(node)
      }
    }
  })

  return treeData
}

// 修改处理添加学生的函数
const handleAddStudent = async () => {
  try {
    const response = await axios.get('http://localhost:8080/organization/findAll')
    console.log(response.data) ;
    if (response.data && response.data.code === 200) {
      // 转换数据为树形结构
      organizationTree.value = convertToTreeData(response.data.t)
      // 打抽屉
      showAddStudentDrawer.value = true
    } else {
      ElMessage.error('获取组织结构失败')
    }
  } catch (error) {
    console.error('获取组织结构失败:', error)
    ElMessage.error('获取组织结构失败')
  }
}

// 添加学生抽屉相关的响式变量
const showAddStudentDrawer = ref(false)
const studentSearchQuery = ref('')
const currentOrg = ref('中软国际教育科技')
const selectedCandidateStudents = ref([])

// 树配置
const defaultProps = {
  children: 'children',
  label: 'label'
}

// 修改待选学生数据的声明，确保是响应式的
const studentsByOrg = ref({})

// 修改搜索处理函数
const handleStudentSearch = async () => {
  if (!studentSearchQuery.value) {
    // 如果搜索框为空，清空学生列表
    studentsByOrg.value[currentOrg.value] = []
    return
  }

  try {
    const response = await axios.get('http://localhost:8080/user/findByNameLike', {
      params: {
        name: studentSearchQuery.value
      }
    })

    // 转换学生数据格式
    const studentList = response.data.map(student => ({
      studentId: student.id,
      name: student.username,
      phone: student.tel
    }))

    // 使用响应式方式更新学生列表
    studentsByOrg.value = {
      ...studentsByOrg.value,
      [currentOrg.value]: studentList
    }

  } catch (error) {
    console.error('搜索学生失败:', error)
    ElMessage.error('搜索学生失败')
    studentsByOrg.value[currentOrg.value] = []
  }
}

// 修改过滤待选学生的计算属性
const filteredCandidateStudents = computed(() => {
  // 获取当前组织的学生列表
  const currentStudents = studentsByOrg.value[currentOrg.value] || []
  return currentStudents
})

// 修改目录树节点点击处理函数
const handleNodeClick = async (data) => {
  try {
    const response = await axios.get('http://localhost:8080/user/findStu', {
      params: {
        organizationId: data.id
      }
    });

    if (response.data.code === 200) {
      // 更新当前组织名称
      currentOrg.value = data.label

      // 转换学生数据格式
      const studentList = response.data.t.map(student => ({
        studentId: student.id,
        name: student.username,
        phone: student.tel
      }));

      // 更新学生列表
      studentsByOrg[currentOrg.value] = studentList;
      selectedCandidateStudents.value = [];
    } else {
      // 清空学生列表并显示提示信息
      studentsByOrg[currentOrg.value] = [];
      ElMessage.warning('当前组织无学生信息');
    }
  } catch (error) {
    console.error('获学生列表失败:', error);
    ElMessage.error('获取学生列表失败');
  }
}

// 处理待选学生表格选择变化
const handleCandidateSelectionChange = (selection) => {
  selectedCandidateStudents.value = selection
}

// 修改处理确认添加的函数
const handleConfirmAdd = async () => {
  if (selectedCandidateStudents.value.length === 0) {
    ElMessage.warning('请选择要添加的学生')
    return
  }
  
  try {
    // 创建 URLSearchParams 对象
    const params = new URLSearchParams()
    params.append('classId', route.params.id)
    // 将学生ID数组转换为字符串后添加
    selectedCandidateStudents.value.forEach(student => {
      params.append('studentsId', student.studentId)
    })

    const response = await axios.post('http://localhost:8080/user/addClassStu',
      params,
      {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      }
    )

    if (response.data.code === 200) {
      ElMessage.success('添加学生成功')
      showAddStudentDrawer.value = false
      // 刷新学生列表
      handleStudentManagement()
    } else {
      ElMessage.error('添加学生失败')
    }
  } catch (error) {
    console.error('添加学生请求失败:', error)
    ElMessage.error('添加学生失败')
  }
}

// 添加组搜索
const orgSearchQuery = ref('')

// 在 script setup 部分添加以代码
const courseStructure = ref(null)

// 修改获取课程目录结构的函数
const fetchCourseStructure = async () => {
  try {
    const courseId = route.params.id
    const response = await axios.get('http://localhost:8080/catalog/showClassCatalog', {
      params: {
        id: courseId
      }
    })

    if (response.data.code === 200) {
      // 将后端数据转换为组件所需的格式
      courseStructure.value = {
        modules: response.data.t.map(module => ({
          id: module.moduleId,
          name: module.moduleName,
          isExpanded: false,
          // 过滤掉 null 课时和资源
          lessons: module.courseHourList
            .filter(lesson => lesson.courseHourId !== null && lesson.courseName !== null)
            .map(lesson => ({
              id: lesson.courseHourId,
              name: lesson.courseName,
              isExpanded: false,
              // 过滤掉 null 的资源
              contents: lesson.resourceList
                .filter(resource => resource.resourceId !== null && resource.resourceName !== null)
                .map(resource => ({
                  id: resource.resourceId,
                  name: resource.resourceName,
                  type: resource.resourceName?.split('.').pop()?.toLowerCase() || '',
                  size: resource.pageCount ? `${resource.pageCount}页` : '-',
                  url: resource.filename
                }))
            }))
        }))
      }
    } else {
      throw new Error(response.data.msg || '获取数据失败')
    }
  } catch (error) {
    console.error('获取课程结构失败:', error)
    ElMessage.error('获取课程结构失败')
  }
}

// 修改删除模块的处理函数
const handleDeleteModule = async (moduleId, event) => {
  // 阻事件冒泡，避免触发展开/收起
  event.stopPropagation()

  try {
    // 显示确认对话框
    await ElMessageBox.confirm(
      '确定要删除这个模块吗？删除后将无法恢复。',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 发送删除请求
    const response = await fetch(`http://192.168.100.53:8080/catalog/deleteModule?id=${moduleId}`, {
      method: 'POST'
    })

    const data = await response.json()

    if (data.code === 200) {
      ElMessage.success('删除成功')
      // 重新获取课程结构数据
      await fetchCourseStructure()
    } else {
      throw new Error(data.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除模块失败:', error)
      ElMessage.error(error.message || '删除失败，请重试')
    }
  }
}

// 修改删除课时的处理函数
const handleDeleteLesson = async (lessonId, event) => {
  // 阻止事件冒泡，避免触发展开/收起
  event.stopPropagation()

  try {
    // 显示确认对话框
    await ElMessageBox.confirm(
      '确定要删除这个课时吗？删除后将无法恢复。',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 送删除请求
    const response = await fetch(`http://192.168.100.53:8080/catalog/deleteModule?id=${lessonId}`, {
      method: 'POST'
    })

    const data = await response.json()

    if (data.code === 200) {
      ElMessage.success('删除成功')
      // 重新获取课结构数据
      await fetchCourseStructure()
    } else {
      throw new Error(data.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除课时失败:', error)
      ElMessage.error(error.message || '删除失败，请重试')
    }
  }
}

onMounted(async () => {
  const courseId = route.params.id
  currentCourse.value = courseData[courseId]
  
  if (!currentCourse.value) {
    console.error('Course not found')
    return
  }
  
  await fetchCourseStructure()
})

// 在 script setup 部分加处理函数
const handleExcelImport = () => {
  showExcelUploadDialog.value = true
}

// Excel上传相关的响应式变量
const showExcelUploadDialog = ref(false)
const uploadStatus = ref('')
const uploadStatusType = ref('info')
const uploadExcelUrl = 'http://localhost:8080/excel/upload'
const uploadExcelData = ref({
  organizationId: 1
})

// 关闭Excel上传对话框
const handleExcelDialogClose = () => {
  showExcelUploadDialog.value = false
  uploadStatus.value = ''
  uploadStatusType.value = 'info'
}

// Excel上传前的验证
const beforeExcelUpload = (file) => {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
                  file.type === 'application/vnd.ms-excel'
  if (!isExcel) {
    ElMessage.error('只能上传Excel文件！')
    return false
  }

  
  // // 设置上传时需要的机构ID
  // uploadExcelData.value.organizationId = uploadExcelData.value.organizationId
  
  uploadStatus.value = '上传中...'
  uploadStatusType.value = 'info'
  return true
}

// Excel上传成功的回调
const handleExcelUploadSuccess = (response) => {
  if (response.code === 200) {
    uploadStatus.value = '上传成功'
    uploadStatusType.value = 'success'
    ElMessage.success(response.msg || '导入成功')
    // 刷新当前选中节点的学生列表
    const currentNode = treeRef.value?.getCurrentNode()
    if (currentNode) {
      handleNodeClick(currentNode)
    }
  } else {
    uploadStatus.value = '上传失败'
    uploadStatusType.value = 'error'
    ElMessage.error(response.msg || '导入失败')
  }
}

// Excel上传失的回调
const handleExcelUploadError = () => {
  uploadStatus.value = '上传失败'
  uploadStatusType.value = 'error'
  ElMessage.error('文件上传失败，请重试')
}

// 确认上传对话框
const handleExcelDialogConfirm = () => {
  if (!uploadStatus.value) {
    ElMessage.warning('请选择文件')
    return
  }
  if (uploadStatus.value === '上传成功') {
    handleExcelDialogClose()
  }
}

// 修改学生管理按钮的点击处理函数
const handleStudentManagement = async () => {
  try {
    const response = await axios.get('http://localhost:8080/user/findClassStu', {
      params: {
        classId: route.params.id
      }
    })

    if (response.data.code === 200) {
      // 转换数据格式
      students.value = response.data.t.map(student => ({
        studentId: student.id,
        name: student.username,
        phone: student.tel
      }))
      showEmptyText.value = false
    } else {
      students.value = []
      showEmptyText.value = true
    }

    showStudentManagementDialog.value = true
  } catch (error) {
    console.error('获取学生列表失败:', error)
    ElMessage.error('获取学生列表失败')
  }
}

// 在 script setup 部分的其他 ref 声明附近添加
const treeRef = ref(null)

// 添加删除内容的处理函数
const handleDeleteContent = async (contentId, event) => {
  // 阻止事件冒泡
  event.stopPropagation()

  try {
    // 显示确认对话框
    await ElMessageBox.confirm(
      '确定要删除这个内容吗？删除后将无法恢复。',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 发送删除请求
    const response = await fetch(`http://192.168.100.53:8080/catalog/deleteModule?id=${contentId}`, {
      method: 'POST'
    })

    const data = await response.json()

    if (data.code === 200) {
      ElMessage.success('删除成功')
      // 重新获取课程结构数据
      await fetchCourseStructure()
    } else {
      throw new Error(data.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除内容失败:', error)
      ElMessage.error(error.message || '删除失败，请重试')
    }
  }
}

// 添加预览相关的响应式变量
const showPreviewDialog = ref(false)
const previewImages = ref([])
const previewVideo = ref('')
const isVideoPreview = ref(false)

// 修改处理预览的函数
const handlePreview = async (content) => {
  try {
    // 获取文件扩展名
    const fileExt = content.name.split('.').pop().toLowerCase()
    
    // 判断是否是视频文件
    if (fileExt === 'mp4') {
      isVideoPreview.value = true
      const response = await fetch(`http://192.168.100.53:8080/catalog/showVideo?id=${content.id}`)
      const data = await response.json()

      if (data.code === 200) {
        previewVideo.value = data.t
        showPreviewDialog.value = true
      } else {
        throw new Error(data.msg || '获取视频预览失败')
      }
    } else {
      // 文档预览
      isVideoPreview.value = false
      const response = await fetch(`http://192.168.100.53:8080/file/preview?id=${content.id}`)
      const data = await response.json()

      if (data.code === 200) {
        previewImages.value = data.t
        showPreviewDialog.value = true
      } else {
        throw new Error(data.msg || '获取预览失败')
      }
    }
  } catch (error) {
    console.error('预览失败:', error)
    ElMessage.error(error.message || '预览失败，请重试')
  }
}
</script>

<style scoped>
.course-detail {
  min-height: 100vh;
  background-color: #f5f7fa;
}

/* 修改顶部样式 */
.blue-header {
  background-color: #4169e1;  /* 蓝色背景 */
  color: white;
  padding: 20px 0;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-info h1 {
  font-size: 20px;
  margin-bottom: 8px;
  color: white;
}

.time {
  font-size: 14px;
  opacity: 0.8;
}

.user-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.icon-btn {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border-radius: 50%;
  transition: all 0.3s;
}

.icon-btn:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.avatar {
  width: 32px;
  height: 32px;
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 功能按钮组样式 */
.function-bar {
  background-color: #4169e1;
  padding: 12px 0;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.function-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.button-group {
  display: flex;
  gap: 12px;
}

.nav-btn {
  padding: 8px 16px;
  border: none;
  background: none;
  color: white;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.3s;
}

.nav-btn:hover, .nav-btn.active {
  background-color: rgba(255, 255, 255, 0.1);
}

.outline-btn {
  padding: 8px 16px;
  border: 1px solid rgba(255, 255, 255, 0.3);
  background: none;
  color: white;
  border-radius: 4px;
  cursor: pointer;
  margin-left: 8px;
  transition: all 0.3s;
}

.outline-btn:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.content-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

.tab-list {
  display: flex;
  gap: 24px;
  margin-bottom: 20px;
  border-bottom: 1px solid #eee;
  padding-bottom: 12px;
}

.tab {
  color: #666;
  cursor: pointer;
  padding: 4px 0;
}

.tab.active {
  color: #4169e1;
  border-bottom: 2px solid #4169e1;
}

.content-tools {
  margin-bottom: 20px;
}

.tool-btn {
  padding: 8px 16px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.tool-btn:hover {
  border-color: #4169e1;
  color: #4169e1;
  background-color: #f5f7fa;
}

.content-list {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
}

.module {
  margin-bottom: 20px;
}

.module-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.module-header:hover {
  background-color: #edf2fd;
}

.module-title {
  font-size: 14px;
  color: #333;
}

.module-actions {
  display: flex;
  gap: 8px;
}

.module-header:hover .module-actions {
  opacity: 1;
}

.action-btn {
  padding: 4px 8px;
  border: none;
  background: none;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.3s;
  color: #666;
}

.action-btn:hover {
  background-color: #e0e6f5;
  color: #4169e1;
}

.icon {
  font-size: 14px;
}

.module-items {
  padding: 0;
  margin-top: 1px;
}

.sub-item {
  padding: 0;
  border-bottom: 1px solid #f0f0f0;
}

.sub-item:last-child {
  border-bottom: none;
}

.sub-item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  color: #333;
  font-size: 14px;
}

.sub-item-content:hover {
  background-color: #f5f7fa;
}

.sub-item-actions {
  display: flex;
  gap: 8px;
}

.sub-action-btn {
  padding: 4px 8px;
  border: none;
  background: none;
  cursor: pointer;
  color: #666;
  font-size: 14px;
  border-radius: 4px;
  transition: all 0.3s;
}

.sub-action-btn:hover {
  background-color: #e0e6f5;
  color: #4169e1;
}

.add-module {
  margin-top: 16px;
  text-align: center;
}

.add-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  width: 100%;
  padding: 12px;
  border: 2px dashed #ddd;
  background: none;
  color: #666;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.add-btn:hover {
  border-color: #4169e1;
  color: #4169e1;
  background-color: #f5f7fa;
}

.plus-icon {
  font-size: 18px;
}

.add-course {
  margin: 16px;
  text-align: center;
}

.add-course .add-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  width: 100%;
  padding: 12px;
  border: 2px dashed #ddd;
  background: none;
  color: #666;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.add-course .add-btn:hover {
  border-color: #4169e1;
  color: #4169e1;
  background-color: #f5f7fa;
}

.third-level {
  background-color: #f9fafb;
  margin: 0 16px;
  border-radius: 4px;
}

.doc-item {
  padding: 12px 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #eee;
}

.doc-content {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #333;
}

.doc-info {
  color: #666;
  font-size: 12px;
}

.doc-actions {
  display: flex;
  gap: 8px;
}

.doc-btn {
  padding: 4px 8px;
  border: none;
  background: none;
  color: #666;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.3s;
}

.doc-btn:hover {
  background-color: #e0e6f5;
  color: #4169e1;
}

.action-group {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 16px;
}

.action-group-btn {
  padding: 6px 12px;
  border: none;
  background: none;
  color: #666;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.3s;
  font-size: 14px;
}

.action-group-btn:hover {
  background-color: #e0e6f5;
  color: #4169e1;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 添加上传相关样式 */
.upload-demo {
  margin-top: 8px;
}

.el-upload__tip {
  color: #666;
  font-size: 12px;
  margin-top: 8px;
}

.student-management {
  padding: 20px;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

.add-student-btn {
  white-space: nowrap;
}

.add-student-drawer :deep(.el-drawer__body) {
  padding: 0;
  display: flex;
  flex-direction: column;
}

.drawer-content {
  display: flex;
  height: 100%;
}

.directory-tree {
  width: 300px;
  border-right: 1px solid #e0e0e0;
  padding: 0;
  overflow-y: auto;
  position: relative;
  display: flex;
  flex-direction: column;
}

.org-search-input {
  padding: 12px;
  border-bottom: 1px solid #e0e0e0;
}

.student-search-input {
  padding: 12px;
  border-bottom: 1px solid #e0e0e0;
}

.student-list {
  flex: 1;
  padding: 0;
  display: flex;
  flex-direction: column;
}

.drawer-footer {
  padding: 16px;
  text-align: right;
  border-top: 1px solid #e0e0e0;
}

.selected-count {
  position: absolute;
  bottom: 20px;
  left: 20px;
  color: #666;
  font-size: 14px;
}

:deep(.el-drawer__header) {
  margin-bottom: 0;
  padding: 16px 20px;
  border-bottom: 1px solid #e0e0e0;
}

:deep(.el-tree) {
  padding: 12px;
}

.tree-header {
  padding: 12px;
  border-bottom: 1px solid #e0e0e0;
}

.excel-import-btn {
  margin-bottom: 12px;
  width: 100%;
}

/* 调整搜索样式移除之前padding */
.org-search-input {
  border-bottom: none;
  padding: 0;
}

.excel-upload {
  text-align: center;
}

.upload-status {
  margin-top: 15px;
  color: #409EFF;
  font-size: 14px;
}

.el-upload__tip {
  font-size: 12px;
  color: #666;
  margin-top: 8px;
}

.preview-container {
  height: calc(100vh - 100px);
  overflow-y: auto;
  padding: 20px;
}

.preview-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.preview-image {
  max-width: 100%;
  height: auto;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

/* 修改文档项样式使其可点击 */
.doc-content {
  cursor: pointer;
  transition: background-color 0.3s;
}

.doc-content:hover {
  background-color: #f5f7fa;
}

/* 自定义滚动条样式 */
.preview-container::-webkit-scrollbar {
  width: 8px;
}

.preview-container::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.preview-container::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 4px;
}

.preview-container::-webkit-scrollbar-thumb:hover {
  background: #555;
}

.preview-video {
  width: 100%;
  max-width: 1200px;
  height: auto;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}
</style> 